<template>
  <div>
    <!-- 面包屑区域 -->
    <Breadcrumb></Breadcrumb>
    <el-card>
      <!-- 添加分类区域 -->
      <el-row>
        <el-col :span="24"
          ><el-button type="primary" @click="showAddCateDialog"
            >添加分类</el-button
          ></el-col
        >
      </el-row>
      <!-- 渲染区域 -->
      <tree-table
        :data="cateData"
        :columns="columns"
        :selection-type="false"
        :expand-type="false"
        show-index
        index-text="#"
        border
        :show-row-hover="false"
      >
        <!-- 是否有效 -->
        <template slot="isok" slot-scope="scope">
          <i
            class="el-icon-success"
            v-if="scope.row.cat_deleted === false"
            style="color: lightgreen"
          ></i>
          <i class="el-icon-error" v-else style="color: red"></i>
        </template>
        <!-- 排序 -->
        <template slot="order" slot-scope="scope">
          <el-tag size="mini" v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag
            size="mini"
            type="success"
            v-else-if="scope.row.cat_level === 1"
            >二级</el-tag
          >
          <el-tag size="mini" type="warning" v-else>三级</el-tag>
        </template>
        <!-- 操作 -->
        <template slot="opt" slot-scope="scope">
          <el-button
            size="mini"
            type="primary"
            icon="el-icon-edit"
            @click="showEditDialogVisible(scope.row.cat_id)"
            >编辑</el-button
          >
          <el-button
            size="mini"
            type="danger"
            icon="el-icon-delete"
            @click="removeCateById(scope.row.cat_id)"
            >删除</el-button
          >
        </template>
      </tree-table>
      <!-- 分页区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="querInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="querInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total"
      >
      </el-pagination>
    </el-card>
    <!-- 添加分类对话框 -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      @close="addCateDialogClosed"
    >
      <el-form
        :model="addCateForm"
        ref="addCateFormRef"
        :rules="addCateFormRules"
      >
        <el-form-item label="分类名称：" prop="cat_name" label-width="100px">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <el-form-item label="父级分类：" label-width="100px">
          <!-- 级联选择器区域 -->
          <!-- options 用来指定数据源 -->
          <!-- props 用来指定配置对象的 -->
          <el-cascader
            v-model="selectdKeys"
            :options="ParentCateList"
            :props="selectOptions"
            @change="parentCateChanged"
            clearable
            change-on-select
          ></el-cascader>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </div>
    </el-dialog>
    <!-- 编辑修改对话框 -->
    <el-dialog title="修改分类" :visible.sync="editDialogVisible">
      <el-form :model="editForm" ref="editFormRef" :rules="editFormRules">
        <el-form-item label="分类名称：" label-width="100px" prop="cat_name">
          <el-input v-model="editForm.cat_name"></el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="editDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editCateUser">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import Breadcrumb from "../Breadcrumb";
export default {
  components: {
    Breadcrumb,
  },
  data() {
    return {
      // 查询条件
      querInfo: {
        type: 3,
        pagenum: 1,
        pagesize: 2,
      },
      // 商品分类的数据列表
      cateData: [],
      // 总数据条数
      total: 0,
      // 为table指定列的定义
      columns: [
        {
          label: "分类名称",
          prop: "cat_name",
        },
        {
          label: "是否有效",
          type: "template",
          // 当前列的名称
          template: "isok",
        },
        {
          label: "排序",
          type: "template",
          // 当前列的名称
          template: "order",
        },
        {
          label: "操作",
          type: "template",
          // 当前列的名称
          template: "opt",
        },
      ],
      // 添加分类的对话框开关
      addCateDialogVisible: false,
      // 添加分类的表单数据对象
      addCateForm: {
        cat_pid: 0, // 父级分类的id
        cat_name: "",
        cat_level: 0, // 默认添加的是一级分类
      },
      // 添加表单的验证规则
      addCateFormRules: {
        cat_name: [
          { required: true, message: "请输分类名称", trigger: "blur" },
        ],
      },
      // 父级分类的列表
      ParentCateList: [],
      // 级联选择器配置对象
      selectOptions: {
        expandTrigger: "hover",
        value: "cat_id",
        label: "cat_name",
        children: "children",
      },
      // 选中的父级分类的Id数组
      selectdKeys: [],
      // 编辑修改对话框开关
      editDialogVisible: false,
      // 编辑回填时获取的分类数据
      editForm: {},
      // 编辑修改规则验证
      editFormRules: {
        cat_name: [
          { required: true, message: "请输入分类名称", trigger: "blur" },
          { min: 1, max: 8, message: "长度在 1 到 8 个字符", trigger: "blur" },
        ],
      },
    };
  },
  created() {
    this.getCateData();
  },
  methods: {
    //   获取商品分类数据的函数
    async getCateData() {
      let { data: res } = await this.$http.get("categories", {
        params: this.querInfo,
      });
      if (res.meta.status !== 200) return this.$message.error(res.meta.msg);
      this.cateData = res.data.result;
      this.total = res.data.total;
      //   console.log(res);
    },
    // 监听pagesoze改变
    handleSizeChange(val) {
      this.querInfo.pagesize = val;
      this.getCateData();
    },
    handleCurrentChange(val) {
      //   console.log(`当前页: ${val}`);
      this.querInfo.pagenum = val;
      this.getCateData();
    },
    // 点击显示添加分类的对话框
    showAddCateDialog() {
      this.getParentCateList(); // 先获取父级分类的数据列表
      this.addCateDialogVisible = true;
    },
    // 获取父级分类的数据列表
    async getParentCateList() {
      let { data: res } = await this.$http.get("categories", {
        params: { type: 2 },
      });
      //   console.log(res);
      if (res.meta.status !== 200)
        return this.$message.error("获取父级分类数据失败！");
      this.ParentCateList = res.data;
    },
    // 级联选择器选择项发生变化触发事件
    parentCateChanged() {
      // 如果selectdKeys 数组的length大于0 证明选中了父级分类
      if (this.selectdKeys.length > 0) {
        // 父级分类的ID
        this.addCateForm.cat_pid = this.selectdKeys[
          this.selectdKeys.length - 1
        ];
        // 为当前分类的等级赋值
        this.addCateForm.cat_level = this.selectdKeys.length;
      } else {
        this.addCateForm.cat_pid = 0;
        this.addCateForm.cat_level = 0;
      }
      //   console.log(this.selectdKeys);
    },
    // 级联选择器 点击确定按钮
    addCate() {
      this.$refs.addCateFormRef.validate(async (valid) => {
        if (!valid) return;
        let { data: res } = await this.$http.post(
          "categories",
          this.addCateForm
        );
        // console.log(res);
        if (res.meta.status !== 201)
          return this.$message.error("添加分类失败！");
        this.$message.success("添加分类成功！");
        this.getCateData();
        this.addCateDialogVisible = false;
      });
    },
    // 监听添加分类关闭事件 重置表单数据
    addCateDialogClosed() {
      this.$refs.addCateFormRef.resetFields();
      this.selectdKeys = [];
      this.addCateForm.cat_pid = 0;
      this.addCateForm.cat_level = 0;
    },
    // 删除分类
    async removeCateById(cateId) {
      let config = await this.$confirm(
        "此操作将永久删除该文件, 是否继续?",
        "提示",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      ).catch((err) => err);
      // console.log(config);
      if (config !== "confirm") return this.$message.info("已取消删除");
      let { data: res } = await this.$http.delete(`categories/${cateId}`);
      // console.log(res);
      if (res.meta.status !== 200) return this.$message.error("删除失败！");
      this.$message.success("删除成功！");
      this.getCateData();
    },
    // 点击编辑按钮触发回填事件
    async showEditDialogVisible(id) {
      let { data: res } = await this.$http.get(`categories/${id}`);
      if (res.meta.status !== 200) return this.$message.error("获取数据失败!");
      this.editForm = res.data;
      // console.log(res);
      this.editDialogVisible = true;
    },
    // 编辑修改 确定提交按钮
    editCateUser() {
      this.$refs.editFormRef.validate(async (valid) => {
        if (!valid) return;
        let { data: res } = await this.$http.put(`categories/${this.editForm.cat_id}`,this.editForm);
        console.log(res);
        if(res.meta.status !==200) return this.$message.error('修改失败！')
        this.$message.success('修改成功！')
        this.getCateData();
        this.editDialogVisible = false;
      });
    },
  },
};
</script>
<style lang="scss" scoped>
.zk-table {
  margin: 15px 0px;
}
.el-cascader {
  width: 100%;
}
</style>